package com.j48.entrancegurad.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.j48.entrancegurad.model.Host;
import com.j48.entrancegurad.model.Picture;
import com.j48.entrancegurad.model.Repair;
import com.j48.entrancegurad.model.User;
import org.apache.commons.fileupload.disk.DiskFileItem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.j48.entrancegurad.service.IRepairService;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;


/***
 * 添加保修数据
 */
@Controller
public class WxRepairsController {
    @Autowired
    private IRepairService repairService;
    @Autowired
    private com.j48.entrancegurad.service.IHostService hostService;
    @Autowired
    private com.j48.entrancegurad.service.IUserService userService;
    @Autowired
            private com.j48.entrancegurad.service.IPictureService pictureService;

    String wxfilename=null;
    /**
     * 微信小程序上传图片
     * @param request
     * @param response
     * @return 返回结果
     * @throws IOException 输入输出异常
     */
    @RequestMapping(value = "/wxRepairs" ,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String wxRepairs(HttpServletRequest request, HttpServletResponse response) throws IOException{
//        String realPath="D:/images";//准备微信小程序传过来的图片的存储路径
        MultipartHttpServletRequest req=(MultipartHttpServletRequest)request;
        MultipartFile multipartFile = req.getFile("file");//通过name值，接收图片文件
        Date date = new Date();
        String myFileName = multipartFile.getOriginalFilename();// 文件原名称
        String fileName =
                Integer.toHexString(new Random().nextInt()) +"."+ myFileName.
                        substring(myFileName.lastIndexOf(".") + 1);
        String path=null;
        String realPath = request.getSession().getServletContext().getRealPath("/");
        System.out.println();
        String trueFileName =fileName;
        String os=System.getProperty("os.name");
        // 设置存放图片文件的路径
        if(os.toLowerCase().startsWith("win")){
            path = "D:/images/"+/*System.getProperty("file.separator")+*/trueFileName;
        }else {
            File mir=new File("/images_j4801/");
            if(!mir.exists()){
                mir.mkdirs();
            }
            path="/images_j4801/"+trueFileName;
        }
        File localFile = new File(path);
        try {

            wxfilename=localFile.getName();//获取图片的名字
            multipartFile.transferTo(localFile);
        }catch (IOException e) {
            e.printStackTrace();
        }catch (IllegalStateException e) {
            e.printStackTrace();
        }
        return  "true";
    }

    /**
     * 微信小程序点击“报修提交”
     * @param request
     * @return
     */
    @RequestMapping(value = "/wxRepairSubmit" ,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String wxRepairSubmit(HttpServletRequest request){
        String repair_describe=request.getParameter("repair_describe");
        ArrayList<Host> list = new ArrayList<>();
        list = (ArrayList<Host>)request.getSession().getAttribute("HostList") ;
        int host_building=list.get(0).getHost_building();//业主所属楼栋
        int host_unit=list.get(0).getHost_unit();//业主所属单元
        int host_housenumber=list.get(0).getHost_housenumber();//业主房间号
        String url="D:/images/"+wxfilename;//报修的图片路径
        int hostId;//业主的id
        Date date = new Date();
        Timestamp repair_createtime=new Timestamp(date.getTime());//获取当前时间，并转换成数据库里的格式
        Host host = new Host(host_building,host_unit,host_housenumber);//实例化对象host
        Host ht=hostService.selectByHouse(host);//查询
        if (ht!=null&&repair_describe!=null&&!repair_describe.equals("")){
            hostId=ht.getHost_id();
            Repair repair = new Repair(repair_describe,url,hostId,repair_createtime);
            if (repairService.repairAdd(repair)){
                return "true";
            }else {
                return "false";
            }
        }else {
            return "false";
        }
    }

    @RequestMapping(value = "/Wxyan",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String Wxtest(org.apache.catalina.servlet4preview.http.HttpServletRequest request){
        User user=new User();
        Host host=new Host();
        String openId=(String) request.getSession().getAttribute("openId");
        user.setUser_open_id(openId);
        User user1=userService.selectByToken(user);
        int host_id=user1.getUser_host_id();
        host.setHost_id(host_id);
        Host  host1=hostService.selectById(host);
        String host_housenumber=host1.getHost_housenumber()+"";
        String host_building=host1.getHost_building()+"";
        String host_unit=host1.getHost_unit()+"";
        ArrayList<String> HostList=new ArrayList<String>();
        HostList.add(host_building);
        HostList.add(host_unit);
        HostList.add(host_housenumber);
        request.getSession().setAttribute("HostList",HostList);
        return "true";
    }

    @RequestMapping(value = "/Wxpicture",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String  Wxpicture(HttpServletRequest request){
        List<Picture> picturesList1= new ArrayList<>();
        picturesList1=pictureService.selectAll();
        ArrayList<String> picturesList = new ArrayList<>();
        if(picturesList1!=null) {
            for (Picture picture : picturesList1) {
                picturesList.add(picture.getPicture_url());
            }
            Collections.reverse(picturesList);
            request.getSession().setAttribute("picturesList",picturesList);
//            System.out.println(picturesList);
//            System.out.println(request.getSession().getServletContext().getRealPath(picturesList.get(0)));
            return JSONArray.toJSONString(picturesList);
        }
        return null;
    }
}
